package ee.ts022.tuum.services.jms;

import java.io.IOException;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import ee.ts022.tuum.domain.Contract;
import ee.ts022.tuum.services.CustomerService;

@Component
public class JmsRestService implements MessageListener {
	
	private static final Logger logger = LoggerFactory.getLogger(JmsRestService.class);

	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private CustomerService customerService;
	
	@Override
	public void onMessage(Message message) {
		if (message instanceof MapMessage) {
			final MapMessage mapMessage = (MapMessage) message;
			
			try {
				if(mapMessage.getString("action").equals("getCustomerContracts")) {
					List<Contract> contracts = customerService.getCustomerContracts(Integer.parseInt(mapMessage.getString("customerId")));
					ObjectMapper mapper = new ObjectMapper();
					jmsTemplate.convertAndSend(mapMessage.getJMSCorrelationID(), mapper.writeValueAsString(contracts));
				}
				
			} catch (JMSException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (JmsException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (JsonGenerationException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (JsonMappingException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (Exception e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}

		} 

	}

}
